<template>
    <div class="app-container">
        <!-- 搜索工作栏 -->
        <el-form
            :model="queryParams"
            ref="queryForm"
            size="small"
            :inline="true"
            v-show="showSearch"
            label-width="68px"
        >
            <el-form-item label="工单名称" prop="workName">
                <el-input
                    v-model="queryParams.workName"
                    placeholder="工单名称"
                    clearable
                    @keyup.enter.native="handleQuery"
                />
            </el-form-item>
            <!-- <el-form-item label="状态" prop="status">
                <el-select
                    v-model="queryParams.status"
                    placeholder="请选择状态"
                    clearable
                    @keyup.enter.native="handleQuery"
                >
                    <el-option :label="'正常'" :value="1"></el-option>
                    <el-option :label="'停用'" :value="0"></el-option>
                </el-select>
            </el-form-item> -->

            <el-form-item label="同步状态" prop="syncStatus">
                <el-select
                    v-model="queryParams.syncStatus"
                    placeholder="同步状态"
                    clearable
                    filterable
                    @keyup.enter.native="handleQuery"
                >
                    <el-option :label="'同步成功'" :value="2"></el-option>
                    <el-option :label="'同步失败'" :value="1"></el-option>
                </el-select>
            </el-form-item>

            <el-form-item
                label="操作人"
                prop="userId"
                v-if="roles.includes('super_admin') || roles.includes('admin')"
            >
                <el-select
                    v-model="queryParams.userId"
                    placeholder="请选操作人"
                    clearable
                    filterable
                    @keyup.enter.native="handleQuery"
                >
                    <el-option
                        :label="item.nickname"
                        :value="item.id"
                        v-for="(item, i) in userList"
                        :key="i"
                    ></el-option>
                </el-select>
            </el-form-item>

            <el-form-item>
                <el-button
                    type="primary"
                    icon="el-icon-search"
                    @click="handleQuery"
                    >搜索</el-button
                >
                <el-button icon="el-icon-refresh" @click="resetQuery"
                    >重置</el-button
                >
            </el-form-item>
        </el-form>
        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button
                    type="primary"
                    plain
                    icon="el-icon-plus"
                    size="mini"
                    @click="openForm({})"
                    >新增</el-button
                >
            </el-col>
            <el-col :span="1.5">
                <el-button
                    plain
                    size="mini"
                    @click="patchDelete"
                    type="danger"
                    icon="el-icon-delete"
                    >批量删除</el-button
                >
            </el-col>
            <!-- <el-col :span="1.5">
                <el-button
                    type="warning"
                    plain
                    icon="el-icon-download"
                    size="mini"
                    @click="handleExport"
                    :loading="exportLoading"
                    v-hasPermi="['tk:worksheet:export']"
                    >导出</el-button
                >
            </el-col> -->
        </el-row>
        <el-table
            v-loading="loading"
            :data="list"
            :stripe="true"
            :show-overflow-tooltip="true"
            border
            size="mini"
            max-height="680"
            @selection-change="handleSelectionChange"
        >
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column
                label="工单ID"
                prop="id"
                width="120"
                align="center"
            />
            <el-table-column label="工单名称" prop="workName" align="center" />
            <el-table-column label="工单类型" prop="workType" align="center">
                <template slot-scope="scope">
                    <el-tag size="mini" :type="'info'">
                        {{
                            {
                                1: "云控",
                            }[scope.row.workType]
                        }}</el-tag
                    >
                </template>
            </el-table-column>

            <el-table-column
                label="工单链接"
                prop="workUrl"
                align="center"
                width="200"
            >
                <template slot-scope="scope">
                    <span v-if="String(scope.row.workUrl) === ''">--</span>
                    <el-tooltip v-else
                        effect="dark"
                        :content="scope.row.workUrl"
                        placement="top"
                        :width="200"
                        :popper-class="'tb-popper-class'"
                    >
                        <span class="point" @click="open(scope.row.workUrl)">{{
                            scope.row.workUrl.length > 30
                                ? scope.row.workUrl.substr(0, 30) + "..."
                                : scope.row.workUrl
                        }}</span>
                    </el-tooltip>
                </template>
            </el-table-column>
            <!-- <el-table-column label="链接URL" prop="linkUrl" align="center">
                <template slot-scope="scope">
                    <el-tag size="mini" class="lk-p">{{
                        scope.row.linkUrl
                    }}</el-tag>
                </template>
            </el-table-column> -->
            <el-table-column label="号码类型" prop="numberType" align="center">
                <template v-slot="scope">
                    {{
                        {
                            1: "WhatsApp",
                            2: "Telegram",
                            3: "Line",
                            4: "自定义",
                        }[scope.row.numberType]
                    }}
                </template>
            </el-table-column>
            <el-table-column label="开始时间" prop="startTime" align="center">
                <template #default="scope">
                    {{
                        scope.row.startTime
                            ? moment(scope.row.startTime).format(
                                  "YYYY-MM-DD HH:mm"
                              )
                            : "--"
                    }}
                </template>
            </el-table-column>
            <el-table-column label="到期时间" prop="endTime" align="center">
                <template #default="scope">
                    {{
                        scope.row.endTime
                            ? moment(scope.row.endTime).format(
                                  "YYYY-MM-DD HH:mm"
                              )
                            : "--"
                    }}
                </template>
            </el-table-column>

            <el-table-column
                prop="targetCompletionNumber"
                align="center"
                width="120"
            >
                <template #header
                    >目标完成数量
                    <el-tooltip
                        class="item"
                        effect="dark"
                        content="每个目标完成总数是"
                        placement="top"
                        ><i class="el-icon-question tips"></i></el-tooltip
                ></template>
                <template #default="scope">
                    {{
                        String(scope.row.targetCompletionNumber) === "null"
                            ? "--"
                            : scope.row.targetCompletionNumber
                    }}
                </template>
            </el-table-column>
            <el-table-column
                prop="quantityBeforeQuantity"
                align="center"
                width="120"
            >
                <template #header
                    >去重前数量
                    <el-tooltip
                        class="item"
                        effect="dark"
                        content="工单去重前数量是"
                        placement="top"
                        ><i class="el-icon-question tips"></i></el-tooltip
                ></template>
                <template #default="scope">
                    {{
                        String(scope.row.quantityBeforeQuantity) === "null"
                            ? "--"
                            : scope.row.quantityBeforeQuantity
                    }}
                </template>
            </el-table-column>

            <el-table-column prop="completedQuantity" align="center" width="120"
                ><template #header
                    >完成数量
                    <el-tooltip
                        class="item"
                        effect="dark"
                        content="每个工单已经完成的数是"
                        placement="top"
                        ><i class="el-icon-question tips"></i
                    ></el-tooltip>
                </template>
                <template #default="scope">
                    {{
                        String(scope.row.completedQuantity) === "null"
                            ? "--"
                            : scope.row.completedQuantity
                    }}
                </template>
            </el-table-column>
            <el-table-column prop="completedRatio" align="center" width="120"
                ><template #header
                    >完成比例(%)
                    <el-tooltip
                        class="item"
                        effect="dark"
                        content="每个工单完成的百分比"
                        placement="top"
                        ><i class="el-icon-question tips"></i></el-tooltip
                ></template>
                <template v-slot="scope">
                    <el-tag
                        size="mini"
                        v-if="scope.row.completedRatio >= 100"
                        >{{ scope.row.completedRatio }}</el-tag
                    >
                    <span v-else>{{
                        String(scope.row.completedRatio) === "null"
                            ? "--"
                            : scope.row.completedRatio
                    }}</span>
                </template>
            </el-table-column>
            <el-table-column
                label="当前速度(h)"
                prop="currentSpeed"
                align="center"
                width="120"
                ><template #header
                    >当前速度(h)
                    <el-tooltip
                        class="item"
                        effect="dark"
                        content="每个工单当前的速度"
                        placement="top"
                        ><i class="el-icon-question tips"></i></el-tooltip
                ></template>
                <template #default="scope">
                    {{
                        String(scope.row.currentSpeed) === "null"
                            ? "--"
                            : scope.row.currentSpeed
                    }}
                </template>
            </el-table-column>
            <el-table-column
                label="号码数量"
                prop="numberQuantity"
                align="center"
            />
            <el-table-column label="同步状态" prop="syncStatus" align="center">
                <template v-slot="scope">
                    <span v-if="!scope.row.syncStatus">--</span>
                    <el-tag
                        v-else
                        style="display: block"
                        :type="
                            scope.row.syncStatus === 2 ? 'success' : 'danger'
                        "
                        size="mini"
                    >
                        {{
                            { 1: "同步失败", 2: "同步成功" }[
                                scope.row.syncStatus
                            ]
                        }}</el-tag
                    >
                </template>
            </el-table-column>

            <!-- <el-table-column label="状态" prop="status" align="center">
                <template v-slot="scope">
                    <el-switch
                        disabled
                        v-model="scope.row.status"
                        :active-value="1"
                        :inactive-value="0"
                    />
                </template>
            </el-table-column> -->
            <el-table-column label="操作人" prop="nickname" align="center">
                <template v-slot="scope">
                    {{
                        scope.row.nickname === "null"
                            ? "--"
                            : scope.row.nickname
                    }}
                </template>
            </el-table-column>
            <el-table-column
                label="操作"
                align="center"
                class-name="small-padding fixed-width"
                width="180"
            >
                <template v-slot="scope">
                    <el-button
                        size="mini"
                        type="text"
                        icon="el-icon-edit"
                        @click="openForm(scope.row)"
                        v-hasPermi="['tk:tourist:update']"
                        >修改</el-button
                    >
                    <el-button
                        size="mini"
                        type="text"
                        icon="el-icon-delete"
                        @click="handleDelete(scope.row)"
                        v-hasPermi="['tk:tourist:delete']"
                        >删除</el-button
                    >
                </template>
            </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <pagination
            v-show="total > 0"
            :total="total"
            :page.sync="queryParams.pageNo"
            :limit.sync="queryParams.pageSize"
            @pagination="getList"
        />
        <AForm ref="formRef" :linksData="linksList" @success="getList" />

        <!-- ...........批量修改状态弹窗............ -->
        <el-dialog title="提示" :visible.sync="dialogVisible" width="300px">
            <div>
                <el-radio-group v-model="switchValue">
                    <el-radio :label="1">开启</el-radio>
                    <el-radio :label="0">关闭</el-radio>
                </el-radio-group>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="updataWorkOrderStatus"
                    >确 定</el-button
                >
            </span>
        </el-dialog>
    </div>
</template>
<script>
import {
    getWorkOrderList,
    deleteWorkOrder,
    exportWorkOrder,
    patchWorkOrderStatus,
    pathDeleteWorkOrder,
} from "@/api/touristwork";
import { getLinksList } from "@/api/links";
import AForm from "./aForm";
import { Loading, Switch } from "element-ui";
import router from "@/router/index";
import moment from "moment";
import { listUser } from "@/api/system/user";
import store from "@/store";
export default {
    components: {
        AForm,
    },
    data() {
        return {
            // 遮罩层
            loading: true,
            // 表格数据
            list: [],
            linksList: [],
            total: 0,
            // 显示搜索条件
            showSearch: true,
            exportLoading: false,
            switchValue: 1,
            dialogVisible: false,
            moment: moment,
            roles: store.getters.roles,
            userList: [],
            queryParams: {
                pageNo: 1,
                pageSize: 10,
                workName: "",
                workUrl: "",
                workType: "",
                status: "",
                userId: "",
            },
            ids: [],
        };
    },
    methods: {
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map((item) => item.id);
        },
        async getList() {
            this.loading = true;
            const { code, data } = await getWorkOrderList(this.queryParams);
            if (code === 0) {
                this.list = data?.list || [];
                this.total = data?.total || 0;
            }

            this.loading = false;
        },
        /** 导出按钮操作 */
        async handleExport() {
            await this.$modal.confirm("是否确认导出所有工单数据项?");
            let downloadLoadingInstance;
            try {
                this.exportLoading = true;
                downloadLoadingInstance = Loading.service({
                    text: "正在导出数据，请稍候",
                    spinner: "el-icon-loading",
                    background: "rgba(0, 0, 0, 0.7)",
                });
                const res = await exportWorkOrder(this.queryParams);
                let routerName = router.app._route.meta.title;
                let fileName = "工单-";
                if (routerName) {
                    fileName = routerName + "-";
                }
                this.$download.excel(
                    res,
                    fileName +
                        this.parseTime(new Date(), "{y}{m}{d}{h}{i}{s}") +
                        ".xls"
                );
            } finally {
                this.exportLoading = false;
                downloadLoadingInstance.close();
            }
        },
        async getLinks() {
            const { code, data } = await getLinksList({
                pageNo: 1,
                pageSize: 3000,
            });
            if (code === 0) {
                this.linksList = data.list;
            }
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNo = 1;
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.resetForm("queryForm");
            this.handleQuery();
        },
        /** 添加/修改操作 */
        openForm(row) {
            this.$refs["formRef"].open(row);
        },
        open(url) {
            window.open(url);
        },
        /** 删除按钮操作 */
        async handleDelete(row) {
            const id = row.id;
            this.$confirm(
                "请注意，该工单信息将被永久删除，请谨慎操作！",
                "提示",
                {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning",
                }
            )
                .then(async () => {
                    try {
                        const res = await deleteWorkOrder({
                            id: id,
                        });
                        if (res.code === 0) {
                            await this.getList();
                            this.$modal.msgSuccess("删除成功");
                        } else {
                            this.$modal.msgError(res.msg);
                        }
                    } catch {}
                })
                .catch(() => {});
        },

        async handleStatusChange(row) {
            const res = await patchWorkOrderStatus({
                status: row.status,
                ids: row.id,
            });
            console.log(res.code, row, "res.code");
            if (res.code === 0) {
                this.$modal.msgSuccess("状态更新成功");
            }
        },

        async getUserList(val) {
            const { code, data } = await listUser(val);
            if (code === 0) {
                this.userList = data.list;
            }
        },

        hasSelectdIds() {
            if (this.ids.length === 0) {
                this.$message.info("请选择要操作的项");
            }
            return this.ids.length > 0;
        },

        async deleteWorkOrders() {
            const { code, msg } = await pathDeleteWorkOrder({
                ids: this.ids.join(","),
            });
            if (code === 0) {
                this.$modal.msgSuccess("删除成功");
                this.getList();
            } else {
                this.$modal.msgError(msg);
            }
        },

        async updataWorkOrderStatus() {
            const { code, msg } = await patchWorkOrderStatus({
                ids: this.ids.join(","),
                status: this.switchValue,
            });
            if (code === 0) {
                this.$modal.msgSuccess("状态更新成功");
                this.dialogVisible = false;
                this.switchValue = 1;
                this.getList();
            } else {
                this.$modal.msgError(msg);
            }
        },

        patchStatus() {
            const hasIds = this.hasSelectdIds();
            if (hasIds) {
                this.dialogVisible = true;
            }
        },

        patchDelete() {
            const hasIds = this.hasSelectdIds();
            if (hasIds) {
                this.$confirm(
                    "请注意，该工单下的所有号码信息将被永久删除，请谨慎操作！",
                    "提示",
                    {
                        confirmButtonText: "确定",
                        cancelButtonText: "取消",
                        type: "warning",
                    }
                )
                    .then(() => {
                        this.deleteWorkOrders();
                    })
                    .catch(() => {
                        this.$message({
                            type: "info",
                            message: "已取消删除",
                        });
                    });
            }
        },
    },
    created() {
        this.getList();
        this.getLinks();
        if (
            store.getters.roles &&
            (store.getters.roles.includes("super_admin") ||
                store.getters.roles.includes("admin"))
        ) {
            this.getUserList({
                pageNo: 1,
                pageSize: 3000,
            });
        }
    },
};
</script>
<style scoped lang="scss">
.tips {
    color: #246dfe;
    font-size: 12px;
}
.point {
    cursor: pointer;
}
</style>
